import { defineStore } from 'pinia'
import { userLoginApi, userLogoutApi, userRegisterApi, getLoginUserApi } from './user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    isAuthenticated: localStorage.getItem('isAuthenticated') === 'true',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
  }),

  getters: {
    isLoggedIn: (state) => state.isAuthenticated,
    isAdmin: (state) => state.userInfo?.userRole === 'admin'
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} credentials - 登录凭证 {userAccount, userPassword}
     */
    async login(credentials) {
      try {
        const data = await userLoginApi(credentials)

        this.isAuthenticated = true
        // START: 核心修复 1
        this.userInfo = {
          id: data.id,
          userAccount: data.userAccount, // 将 account 修正为 userAccount
          userName: data.userName,
          userRole: data.userRole,
          userAvatar: data.userAvatar,
          gender: data.gender
        }
        // END: 核心修复 1

        localStorage.setItem('isAuthenticated', 'true')
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

        ElMessage.success('登录成功')
        return data
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    /**
     * 用户注册
     * @param {Object} data - 注册信息
     */
    async register(data) {
      try {
        const result = await userRegisterApi(data)
        ElMessage.success('注册成功，请登录')
        return result
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    /**
     * 用户登出
     */
    async logout() {
      try {
        await userLogoutApi()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 无论API调用是否成功，都清除本地状态
        this.isAuthenticated = false
        this.userInfo = null
        localStorage.removeItem('isAuthenticated')
        localStorage.removeItem('userInfo')
        ElMessage.success('退出登录成功')
      }
    },

    /**
     * 获取当前登录用户信息
     */
    async fetchCurrentUser() {
      // 不再需要 isAuthenticated 判断，让 API 调用来验证 session
      try {
        const data = await getLoginUserApi()

        // START: 核心修复 2
        this.userInfo = {
          id: data.id,
          userAccount: data.userAccount, // 将 account 修正为 userAccount
          userName: data.userName,
          userRole: data.userRole,
          userAvatar: data.userAvatar,
          gender: data.gender,
          balance: data.balance
        }
        // END: 核心修复 2

        this.isAuthenticated = true
        localStorage.setItem('isAuthenticated', 'true')
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

        return this.userInfo
      } catch (error) {
        console.error('获取用户信息失败（可能是Session过期）:', error)
        // 获取失败，清除所有登录信息
        this.isAuthenticated = false
        this.userInfo = null
        localStorage.removeItem('isAuthenticated')
        localStorage.removeItem('userInfo')
        throw error
      }
    },

    /**
     * 更新用户信息
     * @param {Object} updatedInfo - 要更新的用户信息
     */
    updateUserInfo(updatedInfo) {
      // 确保 userInfo 不为 null
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...updatedInfo }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      }
    }
  }
})